

import 'package:dio/dio.dart';
import 'package:erp/Entity/Product.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/ProductStore.dart';
import 'package:erp/global.dart';

void registerProductEvents(){


  globalBus.subscribe<Product>(Events.PRODUCT_DATA_INSERT_REQUEST, (bus, data) async {
    try {
      var result = await externalInterface.addProduct(AccountStore.signInResult.token, data);
      ProductStore.products.add(result);
      globalBus.publish(Events.PRODUCT_DATA_INSERT_SUCCESS, result);
    }
    catch (exception){
      globalBus.publish(Events.PRODUCT_DATA_INSERT_ERROR, exception);

    }
  });


  globalBus.subscribe(Events.PRODUCT_DATA_SELECT_REQUEST, (bus, data) async {
    var pageCount = await externalInterface.getAllProductCount(AccountStore.signInResult.token);
    var products = <Product>[];
    for (var a = 0; a < pageCount.allPageCount; a++) {
      products.addAll(await externalInterface.getProducts(AccountStore.signInResult.token, a));
    }
    ProductStore.products = products;
    globalBus.publish(Events.PRODUCT_DATA_SELECT_SUCCESS, products);
  });


  globalBus.subscribe<Product>(Events.PRODUCT_DATA_UPDATE_REQUEST, (bus, data) async {
    try {
      var product = await externalInterface.updateProduct(AccountStore.signInResult.token, data);
      var index = ProductStore.products.indexWhere((item) => item.id == data.id);
      ProductStore.products[index] = product;
      globalBus.publish(Events.PRODUCT_DATA_UPDATE_SUCCESS, product);
    }
    catch (exception){
      globalBus.publish(Events.PRODUCT_DATA_UPDATE_ERROR, exception);
    }
  });


  globalBus.subscribe<Product>(Events.PRODUCT_DATA_DELETE_REQUEST, (bus, product) async {
    try {
      await externalInterface.deleteProduct(AccountStore.signInResult.token, product);
      ProductStore.products.removeWhere((item) => item.id == product.id);
      globalBus.publish(Events.PRODUCT_DATA_DELETE_SUCCESS, product);
    }
    catch (exception){
      globalBus.publish(Events.PRODUCT_DATA_DELETE_ERROR, exception);
    }
  });




}


